<template>
	<view class="uni-content" :style="{ paddingTop: top + 'px' }">
		<view class="login-logo">
			<image src="/static/jtlogo.png"></image>
		</view>
		<!-- 顶部文字 -->
		<text class="title title-box">{{ title }}</text>
		<text class="description">{{ description }}</text>
		<u--form ref="loginFormRef" :model="loginData" :rules="loginRules" :errorType="errorType" labelPosition="left">
			<u-form-item @click="showSystem = true">
				<u--input v-model="loginSystemText" class="input-box input-select" placeholder="请选择登录" readonly></u--input>
			</u-form-item>
			<!-- <u-form-item v-if="hasCrewLogin" prop="parameters.workCenterGroup" :rules="loginRules.workCenterGroup" @click="workhideKeyboard">
				<u--input v-model="loginData.parameters.workCenterGroup" class="input-box input-select" placeholder="请选择工作中心分组" readonly></u--input>
			</u-form-item>
			<u-form-item v-if="hasCrewLogin" prop="parameters.workCenterName" :rules="loginRules.workCenterName" @click="hideKeyboard">
				<u--input v-model="loginData.parameters.workCenterName" class="input-box input-select" placeholder="请选择工作中心" readonly></u--input>
			</u-form-item> -->
			<!-- 			<u-form-item v-if="hasCrewLogin" prop="parameters.crewName" @click="crewhideKeyboard">
				<u--input v-model="loginData.parameters.crewName" class="input-box input-select" placeholder="请选择班组" readonly></u--input>
			</u-form-item> -->
			<u-form-item prop="loginName">
				<u--input :focus="focusloginName" @blur="focusloginName = false" class="input-box" clearable v-model="loginData.loginName" placeholder="请输入账号" />
			</u-form-item>
			<u-form-item prop="passWord">
				<u--input :focus="focuspassWord" @blur="focuspassWord = false" class="input-box" clearable type="passWord" v-model="loginData.passWord" placeholder="请输入密码" />
			</u-form-item>
		</u--form>
		<!-- 工作中心分组 picker -->
		<u-picker
			:show="showWorkCenterGroup"
			:columns="workCenterGroupList"
			keyName="label"
			immediateChange
			@cancel="showWorkCenterGroup = false"
			@confirm="workCenterGroupSelect"
		></u-picker>
		<!-- 工作中心 picker -->
		<u-picker :show="showWorkCenter" :columns="workCenterList" keyName="name" immediateChange @cancel="showWorkCenter = false" @confirm="workCenterSelect"></u-picker>

		<!-- 班组 picker -->
		<!-- <u-picker :show="showCrew" :columns="workCrewList" keyName="crewName" immediateChange @cancel="showCrew = false" @confirm="crewSelect"></u-picker> -->

		<button class="uni-btn" type="primary" @click="pwdLogin" :loading="loading">登 录</button>
		<!-- 忘记密码 -->
		<view class="link-box">
			<view>
				<text class="link" @click="toRetrievePwd">忘记密码</text>
			</view>
		</view>
		<!-- 其他操作 -->
		<view class="tool">
			<view @click="jumpTo('/pages/login/scancodeLogin')">
				<view class="iconView">
					<u-icon name="scan" color="#2979ff" size="35px"></u-icon>
				</view>
				<text>扫码</text>
			</view>
			<view @click="jumpTo('/pages/login/ipLogin')">
				<view class="iconView">
					<u-icon name="setting" color="#2979ff" size="35px"></u-icon>
				</view>
				<text>设置</text>
			</view>
		</view>
		<u-action-sheet
			:actions="systemList"
			:title="systemTitle"
			:show="showSystem"
			:closeOnClickOverlay="true"
			:closeOnClickAction="true"
			@select="selectSystem"
			@close="showSystem = false"
		></u-action-sheet>
	</view>
</template>

<script setup lang="ts">
// 导入仓库
import { useUserStore } from "@/stores/useUserStore";
import { reactive, ref, toRaw, computed, watch,onMounted ,getCurrentInstance} from "vue";
import { onShow } from "@dcloudio/uni-app";
import { produceWorkshopList, produceCrewList } from "@/api/common";
import { useDictionaryStore } from "@/stores/useDictionaryStore";
const top = uni.getSystemInfoSync().safeAreaInsets.top;

const title = process.env.VITE_APP_TITLE;
const description = process.env.VITE_APP_DES;

// 登录系统判断
const loginSystemText = computed(
	() =>
		systemList.value.filter(
			(e) => e.value === useUserStore().loginSystemStore
		)[0]?.name
);
const loginSystemValue = computed(
	() =>
		systemList.value.filter(
			(e) => e.value === useUserStore().loginSystemStore
		)[0]?.value
);

const hasCrewLogin = computed(
	() => useUserStore().loginSystemStore === "app:mes"
);

// 登录账号
const loginAccount = computed(
	() => useUserStore().loginAccount
);

// 登录密码
const loginPSW = computed(
	() => useUserStore().loginPSW
);

const systemTitle = ref("请选择登录");
const systemList = ref([
	{
		name: "MES生产",
		value: "app:mes",
	},
	{
		name: "WMS物流",
		value: "app:wms",
	},
	{
		name: "EAM资产",
		value: "app:eam",
	},
]);
const showSystem = ref(false);
function selectSystem(e) {
	if (e.name !== loginSystemText.value) {
		useUserStore().setLoginSystemStore(e.value);
		showSystem.value = false;
		uni.reLaunch({ url: "/pages/login/accountLogin" });
	}
}
async function handleCrewLogin() {
	useUserStore().resetStore();
	//获取字典
	useDictionaryStore()
		.getDictionaryList()
		.then((dictionaryList) => {
			workCenterGroupList[0] = dictionaryList.WorkCenterGroup;
			// 这里可以继续处理 workCenterGroupList
		})
		.catch((error) => {
			console.error("获取 WorkCenterGroup 时发生错误:", error);
		});
	if (loginData.parameters.workCenterGroupValue) {
		const { data } = await produceWorkshopList({
			groupType: loginData.parameters.workCenterGroupValue,
		});
		console.log("", loginData.parameters.workCenterGroupValue);
		console.log("111", data);
		console.log("222", workCenterGroupList[0]);
		data.forEach((item) => {
			item.name = `${item.workshopCode}-${item.workshopName}`;
		});
		workCenterList[0] = data;
		loginData.parameters.workCenterId = "";
	}
	if (loginData.parameters.workCenterId) {
		const res = await produceCrewList({
			workCenterId: loginData.parameters.workCenterId,
		});
		workCrewList[0] = res.data;
	}
}

// 手机端h5可以自动登录
function checkAutoLogin() {
	const systemInfo = uni.getSystemInfoSync();
	if (systemInfo.platform === 'android' || systemInfo.platform === 'ios') {
		return true
	} else {
		return false
	}
}

onShow(async () => {
	// 清空缓存
	// uni.clearStorageSync()
	if (hasCrewLogin.value) {
		handleCrewLogin();
	}
	// #ifdef H5
	setTimeout(()=>{
		if (checkAutoLogin() && loginAccount.value && loginPSW.value && loginSystemText) {
			pwdLogin()
		}
	}, 100)
	// #endif
});

// 显示待开发提示
function showTip() {
	uni.showToast({
		title: "敬请期待",
		icon: "none",
	});
}

// 定义基本表单信息
const loginFormRef = ref();
// const loginData = reactive({
// 	loginName: 'mujinhong',
// 	// passWord: 'pp%@5njj9@owr~Ia',
// 	passWord: '123456mjh',
// 	parameters: hasCrewLogin
// 		? {
// 			    workCenterGroup: '落料', // 工作中心名称
// 				workCenterGroupValue: '0', // 工作中心名称
// 				workCenterId: '1790683947444285442', // 工作中心id
// 				workCenterName: 'lufei666', // 工作中心名称
// 				crewId: '1791391951990894594', // 班组id
// 				crewName: '路飞班组' // 班组name
// 		  }
// 		: {}
// })
const loginData = reactive({
	loginName: loginAccount.value || "",
	// passWord: 'pp%@5njj9@owr~Ia',
	passWord: loginPSW.value || "",
	parameters: hasCrewLogin.value
		? {
				appMenuId: "", // 登录menu类型，物流，生产
				workCenterGroup: "", // 工作中心名称
				workCenterGroupValue: "", // 工作中心名称
				workCenterId: "", // 工作中心id
				workCenterName: "", // 工作中心名称
				crewId: "", // 班组id
				crewName: "", // 班组name
		  }
		: {
				appMenuId: "",
		  },
});

const loginRules = ref({
	// 'parameters.workCenterGroup': {
	// 	type: 'string',
	// 	required: true,
	// 	message: '请选择工作中心分组',
	// 	trigger: ['blur', 'change']
	// },
	// 'parameters.workCenterName': {
	// 	type: 'string',
	// 	required: true,
	// 	message: '请选择工作中心',
	// 	trigger: ['blur', 'change']
	// },
	// 'parameters.crewName': {
	// 	type: 'string',
	// 	required: true,
	// 	message: '请选择班组',
	// 	trigger: ['blur', 'change']
	// },
	loginName: {
		type: "string",
		required: true,
		message: "请输入账号",
		trigger: ["blur", "change"],
	},
	passWord: [
		{
			type: "string",
			required: true,
			message: "请输入密码",
			trigger: ["blur", "change"],
		},
		{
			validator: (rule, value, callback) => {
				if (value.length < 6) {
					return false;
				}
			},
			message: "密码长度不能少于6位",
		},
	],
});

// 定义其他表单信息
const focusloginName = ref(false);
const focuspassWord = ref(false);
const showType = ref(false);
const errorType = ref("toast");

/**
 * 选择工作中心分组
 */
const showWorkCenterGroup = ref(false);
let workCenterGroupList = reactive([]);
async function workCenterGroupSelect(e) {
	if (e.value.length) {
		loginData.parameters.workCenterGroup = e.value[0].label;
		loginData.parameters.workCenterGroupValue = e.value[0].value;
		const { data } = await produceWorkshopList({
			groupType: loginData.parameters.workCenterGroupValue,
		});
		data.forEach((item) => {
			item.name = `${item.workshopCode}-${item.workshopName}`;
		});
		workCenterList[0] = data;
		loginData.parameters.workCenterId = "";
		loginData.parameters.workCenterName = "";
		loginData.parameters.crewId = "";
		loginData.parameters.crewName = "";
	} else {
		loginData.parameters.workCenterId = "";
		loginData.parameters.workCenterName = "";
		loginData.parameters.crewId = "";
		loginData.parameters.crewName = "";
		workCrewList[0] = [];
	}
	showWorkCenterGroup.value = false;
}

/**
 * 选择工作中心
 */
const showWorkCenter = ref(false);
const workCenterList = reactive([]);
async function workCenterSelect(e) {
	if (e.value.length) {
		loginData.parameters.workCenterId = e.value[0].id;
		loginData.parameters.workCenterName = e.value[0].name;
		const { data } = await produceCrewList({ workCenterId: e.value[0].id });
		workCrewList[0] = data;
		loginData.parameters.crewId = "";
		loginData.parameters.crewName = "";
	} else {
		loginData.parameters.workCenterId = "";
		loginData.parameters.workCenterName = "";
		workCrewList[0] = [];
	}
	showWorkCenter.value = false;
}

/**
 * 选择班组
 */
const showCrew = ref(false);
const workCrewList = reactive([]);
// function crewSelect(e) {
// 	if (e.value.length) {
// 		loginData.parameters.crewId = e.value[0].id;
// 		loginData.parameters.crewName = e.value[0].crewName;
// 	} else {
// 		loginData.parameters.crewId = '';
// 		loginData.parameters.crewName = '';
// 	}
// 	showCrew.value = false;
// }

/**
 * 组织键盘弹出
 */
function workhideKeyboard() {
	showWorkCenterGroup.value = true;
	uni.hideKeyboard();
}
/**
 * 组织键盘弹出
 */
function hideKeyboard() {
	showWorkCenter.value = true;
	uni.hideKeyboard();
}
/**
 * 组织键盘弹出
 */
// function crewhideKeyboard() {
// 	showCrew.value = true;
// 	uni.hideKeyboard();
// }

/**
 * 忘记密码
 */
function toRetrievePwd() {
	uni.showToast({
		title: "请联系管理员",
	});
}

/**
 * 登录
 */
const loading = ref(false);
function pwdLogin() {
	if (!loginSystemText.value) {
		uni.showToast({
			title: "请先选择登录",
			icon: "none",
		});
		return false;
	}
	// 记住账号密码
	useUserStore().setLoginAccount(toRaw(loginData.loginName));
	useUserStore().setLoginPSW(toRaw(loginData.passWord));
	loginData.parameters.appMenuId = loginSystemValue.value || "";
	loading.value = true;
	loginFormRef.value
		.validate()
		.then(async (res) => {
			await useUserStore()
				.login(toRaw(loginData))
				.finally(() => (loading.value = false));
		})
		.catch((errors) => {
			console.log("errors", errors);
			loading.value = false;
		});
}
/**
 * 跳转
 */
function jumpTo(url) {
	uni.redirectTo({
		url: url,
	});
}


// 以下为自动登录所有代码
const loginSecret = ref("");
const toPage = ref("");
const autoLoginLoading = ref(false);
onMounted(() => {
	// console.log('getCurrentInstance().proxy', getCurrentInstance().proxy?.options)
	const routerOptions = getCurrentInstance().proxy?.$page?.options;
	loginSecret.value = routerOptions?.loginSecret || "";
	toPage.value = routerOptions?.topage || "";
	if (loginSecret.value && toPage.value) {
		// 开始自动登录
		autoLogin();
	} else {
		autoLoginLoading.value = false;
	}
})
/**
 * 自动登录
 */
async function autoLogin() {
	useUserStore().setLoginSystemStore("app:eam");
	const params = {
		parameters: {
			appMenuId: "app:eam",
		},
		loginSecret: loginSecret.value,
		memberEmpNo: loginSecret.value,
	};
	autoLoginLoading.value = true;
	await useUserStore()
		.login(params, toRaw(toPage.value))
		.finally(() => {
			autoLoginLoading.value = false;
		});
}
</script>

<style lang="scss" scoped>
@import '@/static/css/login-page.scss';

@media screen and (min-width: 690px) {
	.uni-content {
		height: auto;
	}
}

.forget {
	font-size: 12px;
	color: #8a8f8b;
}

.link-box {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	justify-content: space-between;
	margin-top: 20px;
}

.link {
	font-size: 13px;
}
.tool {
	display: flex;
	width: 100%;
	background: #ffffff;
	justify-content: space-evenly;
	margin-top: 20px;

	> view {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		margin: 0 20px;

		& text {
			font-size: 15px;
			font-weight: 400;
			color: #999;
			line-height: 32rpx;
		}

		& .iconView {
			width: 60px;
			height: 60px;
			background: #ecf5ff;
			border-radius: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 10px;
		}
	}
}
.input-select {
	pointer-events: none;
}
</style>
